<style lang="less" scoped>
#search-map {
  width: 100%;
  height: 100%;
  position: relative;
}
.car-search {
  width: 100%;
  height: 100%;
  .map-operation {
    position: absolute;
    top: 32px;
    left: 82px;
  }
}
</style>
<template>
  <div class="car-search">

    <div id="search-map"></div>
    <div class="map-operation">
      <Tooltip content="区域查车">
        <Button type="warning"
                shape="circle"
                icon="ios-crop"
                @click="startDraw"></Button>

      </Tooltip>
      <Input v-model="searchAddr"
             placeholder="请输入地址搜索"
             style="width: 200px"
             element-id="tipinput"
             search="true"
             @on-search="onSearchPlace" />
    </div>
    <Modal title="区域查车"
           v-model="modalVisible"
           :mask-closable="false"
           :width="900"
           :styles="{top: '180px'}"
           :footer-hide="true">
      <Row>
        <Table :loading="loading"
               size="small"
               border
               :columns="columns"
               :data="data"
               max-height="500"
               @on-selection-change="showSelect"
               ref="table"></Table>
      </Row>
    </Modal>

  </div>
</template>

<script>
import AMap from 'AMap'
let mouseTool = null
import {
  getPolygonCarList,
  sendVoice,
  sendSnapshot,
  getSnapshotList
} from '@/api/monitor'
import { plateColorSelect, operationTypeSelect } from '@/libs/dict'

export default {
  name: 'car-search',
  components: {},
  data() {
    return {
      searchAddr: '',
      plateColorSelect: plateColorSelect,
      operationTypeSelect: operationTypeSelect,
      columns: [
        // {
        //   type: 'selection',
        //   width: 60,
        //   align: 'center',
        //   fixed: 'left'
        // },
        {
          title: '运输企业名称',
          key: 'companyName',
          width: 180
        },

        {
          title: '车牌号',
          key: 'licnum',
          width: 100
        },
        {
          title: '车牌颜色',
          key: 'plateColor',
          width: 90,
          render: (h, params) => {
            return h(
              'span',
              this.plateColorSelect.find(item => {
                return item.value == params.row.plateColor
              }).label
            )
          }
        },
        // {
        //   title: 'SIM卡号',
        //   key: 'simCard',
        //   width: 160
        // },

        {
          title: '运营类型',
          key: 'operationType',
          width: 120,
          render: (h, params) => {
            return h(
              'span',
              this.operationTypeSelect.find(item => {
                return item.value == params.row.operationType
              }).label
            )
          }
        },
        {
          title: '车辆状态',
          tooltip: true,
          key: 'carStatus',
          width: 145
        },
        {
          title: 'GPS时间',
          key: 'dataTime',
          width: 150
        },
        {
          title: '速度',
          key: 'speed',
          width: 80
        }
      ],
      data: [],
      total: 0,
      modalVisible: false,
      loading: false
    }
  },
  methods: {
    init() {
      this.mapInit()
    },
    getPolygonCarList(latlng) {
      getPolygonCarList({ latlng: latlng }).then(res => {
        if (res.code == 0) {
          this.data = res.data
        }
      })
    },
    mapInit() {
      this.map = new AMap.Map('search-map', {
        resizeEnable: true,
        zoom: 5
      })
      let self = this
      this.map.plugin(['AMap.MapType'], function() {
        //地图类型切换
        var type = new AMap.MapType({
          defaultType: 0 //使用2D地图
        })
        self.map.addControl(type)
      })
      this.map.plugin(['AMap.ToolBar'], function() {
        //加载工具条
        var tool = new AMap.ToolBar()
        self.map.addControl(tool)
      })
      this.map.plugin(['AMap.MouseTool'], function() {
        //鼠标工具插件
        mouseTool = new AMap.MouseTool(self.map)
      })
      AMap.event.addListener(mouseTool, 'draw', function(event) {
        // event.obj 为绘制出来的覆盖物对象
        let drawObj = event.obj
        let points = drawObj.getPath()
        let newpoints = []
        points.forEach(item => {
          newpoints.push(`${item.lat},${item.lng}`)
        })
        self.modalVisible = true
        self.getPolygonCarList(newpoints.join('|'))

        mouseTool.close(false)
      })
      //输入提示
      var autoOptions = {
        input: 'tipinput'
      }
      var placeSearch = null
      var auto = null
      this.map.plugin(['AMap.Autocomplete'], function() {
        auto = new AMap.Autocomplete(autoOptions)
      })

      this.map.plugin(['AMap.PlaceSearch'], function() {
        placeSearch = new AMap.PlaceSearch({
          map: self.map
        }) //构造地点查询类
      })

      AMap.event.addListener(auto, 'select', select) //注册监听，当选中某条记录时会触发
      function select(e) {
        placeSearch.setCity(e.poi.adcode)
        placeSearch.search(e.poi.name) //关键字查询查询
      }
    },
    onSearchPlace() {
      let addr = this.searchAddr
      let self = this
      AMap.plugin('AMap.Geocoder', function() {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        })

        geocoder.getLocation(addr, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // result中对应详细地理坐标信息
            var location = result.geocodes[0].location
            try {
              if (location) {
                self.map.setZoomAndCenter(14, [location.lng, location.lat])
              } else {
                self.$Message.error('未查询到地理信息!')
              }
            } catch (error) {
              self.$Message.error('查询地理信息失败,请检查网络!')
            }
          } else {
            self.$Message.error('未查询到地理信息!')
          }
        })
      })
    },
    startDraw() {
      this.map.clearMap()
      //矩形
      mouseTool.rectangle({
        strokeColor: 'red',
        strokeOpacity: 0.5,
        strokeWeight: 6,
        fillColor: 'blue',
        fillOpacity: 0.5,
        // strokeStyle还支持 solid
        strokeStyle: 'solid'
        // strokeDasharray: [30,10],
      })
      this.$Message.info('点击鼠标左键确定左上角，松开鼠标完成确定矩形右下角')
    },
    submitVoice() {
      if (this.sendVoiceText) {
        sendVoice({ carId: this.targetCarId, text: this.sendVoiceText }).then(
          res => {
            if (res.code == 0) {
              this.$Message.success('下发成功')
              this.voiceModalVisible = false
            } else {
              this.$Message.error(res.msg)
            }
          }
        )
      } else {
        this.$Message.error('请填写消息内容')
      }
    }
  },
  mounted() {
    this.init()
  }
}
</script>